package student_c

import (
	"Student_Mental/DBconfing"
	"Student_Mental/controller/wsService"
	"Student_Mental/model"
	_ "database/sql"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"html"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func returnErr(err error, c *gin.Context) {

	if err != nil {
		c.JSON(200, gin.H{
			"code":  1,
			"msg":   err.Error(),
			"title": "1231241243",
		})
	}
}

// ListTest
// @Tags 学生端
// @summary 获取试卷列表
// @Param id header   string false "学生ID"
// @Success 200 {string} json{"code","data"}
// @Router /student/test [get]
func ListTest(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	id, _ := c.Cookie("Id")
	rows, err := sqlDb.Query("SELECT * FROM Paper where status!=-1 and title not in (SELECT paper_name FROM testrecord WHERE stu_id = ?)", id)
	returnErr(err, c)
	//遍历打印
	var queList []model.Paper
	for rows.Next() {
		var s model.Paper
		err = rows.Scan(&s.Id, &s.Title, &s.Status, &s.ScoreLine, &s.Score, &s.Context, &s.CreatedBy, &s.CreateTime)
		data := model.Paper{
			Id:         s.Id,
			Title:      s.Title,
			Status:     s.Status,
			ScoreLine:  s.ScoreLine,
			Score:      s.Score,
			Context:    s.Context,
			CreatedBy:  s.CreatedBy,
			StringTime: s.CreateTime.Format("2006-01-02 15:04:05"),
		}
		queList = append(queList, data)
	}

	c.HTML(http.StatusOK, "test_list.html", gin.H{
		"code": 0,
		"data": queList,
	})
	//用完关闭
	rows.Close()
	sqlDb.Close()
}

// TakeTheExam
// @Tags 学生端
// @summary 抽调试卷
// @Param id path string false "试卷ID"
// @Router /student/test/{id} [get]
func TakeTheExam(c *gin.Context) {
	id := c.Param("id")
	sqlDb, _ := DBconfing.Mysql()
	var status string
	sqlDb.QueryRow("SELECT status FROM Paper where id=" + id).Scan(&status)
	if status == "1" {
		c.HTML(200, "takeTest.html", gin.H{
			"paperId": id,
		})
	} else {
		c.HTML(200, "404.html", gin.H{
			"code": -1,
			"msg":  "该试卷已经下架",
		})
	}
	sqlDb.Close()
}

// CheckTheExam
// @Tags 学生端
// @summary 答题情况
// @Param paperId path string false "试卷ID"
// @Param id path string false "答题记录ID"
// @Router /student/test/record/check/{paperId}/{id} [get]
func CheckTheExam(c *gin.Context) {
	recordId := c.Param("id")
	paperId := c.Param("paperId")
	sqlDb, _ := DBconfing.Mysql()
	var resList string
	err := sqlDb.QueryRow("SELECT res_list FROM testrecord where id=" + recordId).Scan(&resList)
	returnErr(err, c)
	c.HTML(200, "checkTest.html", gin.H{
		"paperId": paperId,
		"resList": resList,
	})
	sqlDb.Close()
}

// RecordTest
// @Tags 学生端
// @summary 新增考试记录
// @Router /student/Paper/record/{id} [post]
func RecordTest(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	PaperId := c.Param("id")
	stuid := c.PostForm("stu_id")
	reslist := c.PostForm("res_list")
	score := c.PostForm("score")
	if reslist != "" {
		rs, err := sqlDb.Exec("insert into testrecord(stu_id,paper_id,paper_name,res_list,score,create_time)values (?,?,(select  title from Paper WHERE Paper.id=?),?,?,?)", stuid, PaperId, PaperId, reslist, score, time.Now().Format("2006-01-02 15:04:05"))
		returnErr(err, c)
		lastInsertId, err := rs.LastInsertId()
		if PaperId == "1" {
			sqlDb.Exec("update scl90 set textId=? where userId=?", lastInsertId, stuid)
		}
		rowCount, err := rs.RowsAffected()
		returnErr(err, c)
		if rowCount > 0 {
			c.JSON(200, gin.H{
				"code": 0,
			})
		} else {
			returnErr(err, c)
		}
	}
	sqlDb.Close()
}

// RecordScl90 处理scl-90
func RecordScl90(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	defer sqlDb.Close()
	//PaperId := c.Param("id")
	//score := c.PostForm("score")
	stuid := c.PostForm("stu_id")
	counts := make(map[string]int)      //10个因子
	counts2 := make(map[string]int)     //阴阳项目
	counts3 := make(map[string]int)     //阴阳项目总分
	counts4 := make(map[string]float64) //10个因子均分
	reslist := c.PostForm("res_list")
	//if reslist != "" {
	//	sqlDb.Exec("insert into testrecord(stu_id,paper_id,paper_name,res_list,score,create_time)values (?,?,(select  title from Paper WHERE Paper.id=?),?,?,?)", stuid, PaperId, PaperId, reslist, score, time.Now().Format("2006-01-02 15:04:05"))
	//}
	reslist = strings.Trim(reslist, "[]") // 去除字符串中的方括号
	numStr := strings.Split(reslist, ",") // 拆分字符串为字符串切片
	if reslist != "" {
		for i, s := range numStr {
			num, _ := strconv.Atoi(s)
			switch i + 1 {
			case 1, 4, 12, 27, 40, 42, 48, 49, 52, 53, 56, 58:
				counts["躯体化"] += num
			case 3, 9, 10, 28, 38, 45, 46, 51, 55, 65:
				counts["强迫症状"] += num
			case 6, 21, 34, 36, 37, 41, 61, 69, 73:
				counts["人际关系敏感"] += num
			case 5, 14, 15, 20, 22, 26, 29, 30, 31, 32, 54, 71, 79:
				counts["抑郁"] += num
			case 2, 17, 23, 33, 39, 57, 72, 78, 80, 86:
				counts["焦虑"] += num
			case 11, 24, 63, 67, 74, 81:
				counts["敌对"] += num
			case 13, 25, 47, 50, 70, 75, 82:
				counts["恐怖"] += num
			case 8, 18, 43, 68, 76, 83:
				counts["偏执"] += num
			case 7, 16, 35, 62, 77, 84, 85, 87, 88, 90:
				counts["精神病性"] += num
			case 19, 44, 59, 60, 64, 66, 89:
				counts["其他"] += num
			default:
				fmt.Println(i+1, s, "in Unknown")
				// 未知情况的处理逻辑
			}
			if num == 1 {
				counts2["阴性项目"]++
			} else {
				counts2["阳性项目"]++
				counts3["阳性分数"] += num
			}
		}
	} // 遍历 Map
	var sum int
	for _, v := range counts {
		sum += v
	}
	var average float32      //总均分
	var masculineAge float32 //阳性均分
	average = float32(sum) / 90
	masculineAge = float32(counts3["阳性分数"]) / float32(counts2["阳性项目"])
	counts4["躯体化"] = Decimal(float64(counts["躯体化"]) / 12)
	counts4["强迫症状"] = Decimal(float64(counts["强迫症状"]) / 10)
	counts4["人际关系敏感"] = Decimal(float64(counts["人际关系敏感"]) / 9)
	counts4["抑郁"] = Decimal(float64(counts["抑郁"]) / 13)
	counts4["焦虑"] = Decimal(float64(counts["焦虑"]) / 10)
	counts4["敌对"] = Decimal(float64(counts["敌对"]) / 6)
	counts4["恐怖"] = Decimal(float64(counts["恐怖"]) / 7)
	counts4["偏执"] = Decimal(float64(counts["偏执"]) / 6)
	counts4["精神病性"] = Decimal(float64(counts["精神病性"]) / 10)
	counts4["其他"] = Decimal(float64(counts["其他"]) / 7)
	// 格式化平均值为两位小数
	averageStr := fmt.Sprintf("%.2f", average)
	masculineAgeStr := fmt.Sprintf("%.2f", masculineAge)
	// 插入数据
	query := `INSERT INTO scl90 (userId,somatization, obsessiveCompulsive, interpersonalSensitivity, depression, anxiety, hostile, terror, bigotry, psychotic, other, sum, average, masculine, feminine,masculineSum,masculineAge)
			  VALUES (? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
	result, err := sqlDb.Exec(query, stuid, counts4["躯体化"], counts4["强迫症状"], counts4["人际关系敏感"], counts4["抑郁"], counts4["焦虑"], counts4["敌对"], counts4["恐怖"], counts4["偏执"], counts4["精神病性"], counts4["其他"], sum, averageStr, counts2["阳性项目"], counts2["阴性项目"], counts3["阳性分数"], masculineAgeStr)
	if err != nil {
		fmt.Println("插入数据失败:", err)
		return
	}
	rowsAffected, err := result.RowsAffected()
	if err != nil {
		fmt.Println("获取受影响行数失败:", err)
		return
	}
	if rowsAffected > 0 {
		c.JSON(200, gin.H{
			"code": 0,
		})
	}
	fmt.Println(counts, counts2, counts3, sum, averageStr, masculineAgeStr)
}
func Decimal(value float64) float64 {
	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
	return value
}

// RecordList
// @Tags 学生端
// @summary 获取考试记录列表
// @Router /student/test/record/list [get]
func RecordList(c *gin.Context) {
	Id, err := c.Cookie("Id")
	returnErr(err, c)
	sqlDb, _ := DBconfing.Mysql()
	rows, err1 := sqlDb.Query("SELECT * FROM testrecord where stu_id=" + Id)
	returnErr(err1, c)
	var RecordList []model.TestRecord
	for rows.Next() {
		var s model.TestRecord
		err = rows.Scan(&s.Id, &s.StuId, &s.PaperName, &s.PaperId, &s.ResList, &s.Score, &s.CreateTime)
		data := model.TestRecord{
			Id:         s.Id,
			StuId:      s.StuId,
			PaperName:  s.PaperName,
			PaperId:    s.PaperId,
			ResList:    s.ResList,
			Score:      s.Score,
			StringTime: s.CreateTime.Format("2006-01-02 15:04:05"),
		}
		RecordList = append(RecordList, data)
	}
	c.HTML(200, "recordList.html", gin.H{
		"data": RecordList,
	})
	rows.Close()
	sqlDb.Close()
}

// GetCarousel
// @Tags 学生端
// @summary 获取轮播图
// @Router /student/carousel [get]
func GetCarousel(c *gin.Context) {
	var carousel_list []model.Carousel
	sqlDb, _ := DBconfing.Mysql()
	rows, err := sqlDb.Query("SELECT * from Carousel")
	if err != nil {
		println("结果为空")
		return
	}
	//遍历打印
	for rows.Next() {
		var s model.Carousel
		err = rows.Scan(&s.Id, &s.Title, &s.Context, &s.Url, &s.Link, &s.CreateTime)
		data := model.Carousel{
			Id:         s.Id,
			Title:      s.Title,
			Context:    s.Context,
			Url:        s.Url,
			Link:       s.Link,
			StringTime: s.CreateTime.Format("2006-01-02 15:04:05"),
		}
		carousel_list = append(carousel_list, data)
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": carousel_list,
	})
	//用完关闭
	rows.Close()
	sqlDb.Close()
}

// TeacherList
// @Tags 学生端
// @summary 咨询老师列表
// @Router /teacher/client [get]
func TeacherList(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	rows, err1 := sqlDb.Query("SELECT MIN(id) as id, teacher_name, MIN(room_id) as room_id, MIN(avatar) as avatar FROM teacher, room WHERE room.uid1 = id OR room.uid2 = id GROUP BY teacher_name;")
	red, _ := DBconfing.ConnRedis()
	defer red.Close()
	returnErr(err1, c)
	M := wsService.Message{}
	var TeacherList []model.ClientTeacher
	for rows.Next() {
		var s model.ClientTeacher
		rows.Scan(&s.Id, &s.Name, &s.RoomId, &s.Avatar)
		firstElement, _ := red.LIndex(strconv.Itoa(s.RoomId), 0).Result()
		if firstElement != "" {
			json.Unmarshal([]byte(firstElement), &M)
			if M.Type == "pic" {
				firstElement = "[图片]"
			} else {
				firstElement = M.Content
			}
		}
		// 解码HTML标记
		decodedStr := html.UnescapeString(firstElement)
		data := model.ClientTeacher{
			Id:         s.Id,
			Name:       s.Name,
			RoomId:     s.RoomId,
			NewMessage: decodedStr,
			Avatar:     s.Avatar,
		}
		TeacherList = append(TeacherList, data)
	}
	c.HTML(200, "teacherList.html", gin.H{
		"data": TeacherList,
	})
	rows.Close()
	sqlDb.Close()
}
func GetBooking(c *gin.Context) {
	var bookingList []model.Booking
	student := c.Param("id")
	sqlDb, _ := DBconfing.Mysql()
	rows, err := sqlDb.Query("SELECT * from booking where student_id=?", student)
	defer rows.Close()
	if err != nil {
		println("结果为空")
		return
	}
	for rows.Next() {
		var booking model.Booking
		err := rows.Scan(&booking.Id, &booking.StudentId, &booking.TeacherId, &booking.Place, &booking.State, &booking.Content, &booking.BookingTime, &booking.CreateTime)
		sqlDb.QueryRow("(SELECT student_name FROM student WHERE id = ?)UNION(SELECT teacher_name FROM teacher WHERE id = ?)LIMIT 1;", booking.TeacherId, booking.TeacherId).Scan(&booking.TeacherName)
		sqlDb.QueryRow("(SELECT student_name FROM student WHERE id = ?)UNION(SELECT teacher_name FROM teacher WHERE id = ?)LIMIT 1;", student, student).Scan(&booking.StudentName)
		booking.StringTime = booking.CreateTime.Format("2006-01-02 15:04:05")
		if err != nil {
			log.Fatal(err)
		}
		switch booking.State {
		case 1:
			booking.StateName = "发起"
			break
		case 2:
			booking.StateName = "接受"
			break
		case 3:
			booking.StateName = "完成"
			break
		case 4:
			booking.StateName = "取消"
			break
		case 5:
			booking.StateName = "失效"
			break
		}
		bookingList = append(bookingList, booking)
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": bookingList,
	})
}
